<template>
  <div class="device-detail-dialog-page">
    <el-dialog
      :model-value="props.dialogVisible"
      title="设备详情"
      width="1000px"
      :close-on-click-modal="false"
      :before-close="handleClose">
      <div class="info-block">
        <div>
          <span>基本信息</span>
        </div>
        <el-row class="mt16" :gutter="16">
          <el-col class="info-item" :span="8" v-for="(item, index) in infoData" :key="index">
            <span class="label">{{item.label}}:</span>
            <span v-if="item.prop === 'dataLatestTime'" class="value">
              {{deviceForm[item.prop] ? moment(deviceForm[item.prop]).format('YYYY-MM-DD HH:mm:ss') : ''}}
            </span>
            <span v-else class="value">{{deviceForm[item.prop]}}</span>
          </el-col>
        </el-row>
      </div>
      <div class="user-block">
        <div>
          <span>绑定用户</span>
          <span class="btn">
            <el-button type="primary" @click="batchBindUser">绑定用户</el-button>
            <el-button @click="batchDeleteUser">解除绑定</el-button>
          </span>
        </div>
        <el-table ref="multipleTableRef" :data="tableData" :max-height="400" class="nr-table mt16">
          <el-table-column type="selection" width="30"/>
          <el-table-column label="绑定关系" prop="role">
            <template #default="scope">
              <span>{{scope.row.role === 1 ? '使用者' : '管理员'}}</span>
            </template>
          </el-table-column>
          <el-table-column label="用户名称" prop="username"></el-table-column>
          <!-- <el-table-column label="备注名称" prop="rtsp"></el-table-column> -->
          <el-table-column label="分组" prop="projectName"></el-table-column>
          <el-table-column label="绑定手机" prop="phoneNum"></el-table-column>
          <el-table-column label="绑定微信" prop="wechatName"></el-table-column>
          <el-table-column label="最后登录时间" prop="logInTimeLast">
            <template #default="scope">
              <span>{{scope.row.logInTimeLast ? moment(scope.row.logInTimeLast).format('YYYY-MM-DD HH:mm:ss') : ''}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-link class="table-btn" type="danger" :underline="false" @click="handleDeleteUser(scope.row)">解绑</el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <device-bind-user-dialog
      :dialogVisible="selectUserDialogVis"
      :formData="deviceForm"
      @update:dialogVisible="(value: boolean) => selectUserDialogVis = value"
      @submit="getBindUserList">
    </device-bind-user-dialog>
  </div>
</template>

<script setup lang="ts" name="DeviceDetailDialog">
import { ref, reactive, watch, ComponentInternalInstance, getCurrentInstance, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import DeviceBindUserDialog from './device-bind-user-dialog.vue'
import { bindUserList, unbindBatch } from '@/api/bind'
import moment from 'moment'

const { proxy } = getCurrentInstance() as ComponentInternalInstance

const emit = defineEmits(['update:dialogVisible'])
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: {}
  }
})

const deviceForm = reactive({
  id: -1,
  deviceName: '',
  deviceSn: '',
  productName: '',
  projectName: '',
  dataLatestTime: '',
  address: '',
  location: ''
})
const infoData = ref<any>([
  { label: '设备名称', prop: 'deviceName' },
  { label: '设备ID', prop: 'deviceSn' },
  { label: '产品', prop: 'productName' },
  { label: '设备分组', prop: 'projectName' },
  { label: '安装时间', prop: '' },
  { label: '最近数据时间', prop: 'dataLatestTime' },
  { label: '安装人员', prop: '' },
  { label: '安装地址', prop: 'address' },
  { label: '安装房间', prop: 'location' },
  { label: '安装位置', prop: '' }
])
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const tableData = ref<any>([])
const selectUserDialogVis = ref(false)

watch(() => props.dialogVisible, async (newVal) => {
  if (newVal) {
    deviceForm.id = props.formData.deviceId
    deviceForm.deviceName = props.formData.deviceName
    deviceForm.deviceSn = props.formData.deviceSn
    deviceForm.productName = props.formData.productName
    deviceForm.projectName = props.formData.projectName
    deviceForm.dataLatestTime = props.formData.dataLatestTime
    deviceForm.address = props.formData.address
    deviceForm.location = props.formData.location
    getBindUserList()
  }
})

// 绑定用户
const batchBindUser = () => {
  selectUserDialogVis.value = true
}

// 批量解绑
const batchDeleteUser = () => {
  let arr = <any>[...multipleTableRef.value?.getSelectionRows()]
  if (arr.length === 0) {
    ElMessage.error(`未选择用户！`)
    return false
  }
  ElMessageBox.confirm(
    `确定要批量解绑用户吗？`,
    '系统提示',
    {
      type: 'warning',
    }
  )
  .then(() => {
    let bindIds = <any>[]
    arr.map((item: any) => {
      bindIds.push(item.bindId)
    })
    let params = {
      bindIdList: bindIds
    }
    unbindBatch(params).then((res: any) => {
      if (res.code === 0) {
        ElMessage.success(`解绑成功！`)
        getBindUserList()
      } else {
        ElMessage.error(`${res.msg}`)
      }
    }).catch(err => {
      console.log(err)
    })
  })
  .catch(() => {})
}

// 解绑
const handleDeleteUser = (row: any) => {
  ElMessageBox.confirm(
    `确定要解绑【${row.username}】此用户吗？`,
    '系统提示',
    {
      type: 'warning',
    }
  )
  .then(() => {
    let params = {
      bindIdList: [row.bindId]
    }
    unbindBatch(params).then((res: any) => {
      if (res.code === 0) {
        ElMessage.success(`解绑成功！`)
        getBindUserList()
      } else {
        ElMessage.error(`${res.msg}`)
      }
    }).catch(err => {
      console.log(err)
    })
  })
  .catch(() => {})
}

// 关闭弹窗
const handleClose = () => {
  tableData.value = []
  proxy?.$emit('update:dialogVisible', false)
}

// 获取绑定设备
const getBindUserList = async () => {
  let params = {
    deviceId: deviceForm.id
  }
  await bindUserList(params).then((res: any) => {
    if (res.code === 0) {
      tableData.value = [...res.list]
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
}
</script>

<style lang="stylus" scoped>
@import '../../style/base.styl'

.device-detail-dialog-page
  .info-item
    margin-bottom 16px
    .label
      width 100px
      display inline-block
      text-align right
      color black
      font-weight bold
    .value
      margin-left 4px
  .user-block
    .btn
      margin-left 16px
</style>
